<?php
namespace app\admin\controller\supply;

use app\admin\model\SupplyQuoted;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use app\common\controller\SupplyController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use Exception;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\App;
use think\facade\Filesystem;
use think\facade\Request;

/**
 * Class Quoted
 * @package app\admin\controller\supply
 * @ControllerAnnotation(title="报价管理")
 */
class Quoted extends SupplyController
{

    use Curd;

    protected $relationSearch = true;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SupplyQuoted();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->withJoin('admin', 'LEFT')
                ->with('product', 'LEFT')
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    public function import()
    {
        if ($this->request->isPost()) {

            $xlsFile = Request::post('excel');

            //3.  第三方插件 载入表格
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
            $reader->setReadDataOnly(TRUE);
            $spreadsheet = $reader->load($xlsFile); //载入excel表格

            //4.  获取总行数 总列数
            $worksheet = $spreadsheet->getActiveSheet();
            $highestRow = $worksheet->getHighestRow(); // 总行数
            $highestColumn = $worksheet->getHighestColumn(); // 总列数

            //5.  判断表格内是否有数据
            if ($highestRow <= 1) {
                $this->error('Excel表格中没有数据，请重新选择文件或检查文件是否保存');
            }

            //6.   循环出表格数据 组成数组
            $data = [];
            for ($row = 2; $row <= $highestRow; ++$row) {
                $product_id = $worksheet->getCellByColumnAndRow(1, $row)->getValue(); //产品id
                $specs = $worksheet->getCellByColumnAndRow(2, $row)->getValue(); //规格
                $price = $worksheet->getCellByColumnAndRow(3, $row)->getValue(); //价格
                $company_id = $worksheet->getCellByColumnAndRow(4, $row)->getValue(); //厂家id
                $admin_id = session('admin.id');//操作人ID


                $data[] = [
                    'product_id' => $product_id,
                    'specs'   => $specs,
                    'price' => $price,
                    'company_id' => $company_id,
                    'admin_id' => $admin_id,
                    'create_time' => time()
                ];
            }

            // 7.  用 DB 方法将数据插入数据库
            $res = $this->model->saveAll($data);
            
            // // 8.  返回回调
            if ($res) {
                $data = [];
                $this->success('导入成功');
            }
        } 
        return $this->fetch();
    }

    /**
     * 模板生成
    */
    public function create_xlsx()
    {
         //1.  设置表格默认文本
         $spreadsheet = new Spreadsheet();
         $sheet = $spreadsheet->getActiveSheet();
         $sheet->setCellValue('A1', '产品id');
         $sheet->setCellValue('B1', '规格');
         $sheet->setCellValue('C1', '价格');
         $sheet->setCellValue('D1', '厂家id');
 
         //8.  设置文件名 强制浏览器下载表格
         $filename = 'quoted.xlsx';
         header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
         header('Content-Disposition: attachment;filename="' . $filename . '"');
         header('Cache-Control: max-age=0');
 
         $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
         $writer->save('php://output');
     }

     public function upload()
     {
         //1.  获取上传文件信息并实例它
         $file = request()->file('file');
 
         //2.  应用根目录 Env::get('root_path')  拼接路径  此目录将用来存放上传文件
         $xlsUploads =  'excel';
 
         //3.  判断目录存在否 不存在生成新目录 
         if (!file_exists($xlsUploads)) {
             mkdir($xlsUploads);
         }
        //  dump($file);
 
         // move() 将文件移动的方法
        //  $info = $file->save($xlsUploads);
         $savename = Filesystem::disk('public')->putFile('excel',$file);
         
 
         // 4.  返回结果数组  src 返回路径的后两部分
         return json([
             'code' => 0,
             'msg' => '',
             'data' => [
                 'src' => $savename
             ]
         ]);
     }
    
}